package com.ttsx.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ttsx.handler.CategoryCellStyleHandler;
import com.ttsx.listener.CategoryListener;
import com.ttsx.mapper.CategoryMapper;
import com.ttsx.pojo.converter.CategoryConverter;
import com.ttsx.pojo.entity.Category;
import com.ttsx.pojo.vo.CategoryEeVO;
import com.ttsx.service.CategoryService;
import com.ttsx.service.ProductService;
import com.ttsx.core.common.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lucky
 * @description 针对表【ttsx_category(分类表)】的数据库操作Service实现
 * @createDate 2025-03-01 17:41:06
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Autowired
    private ProductService productService;

    @Cacheable(value = "category", keyGenerator = "keyGenerator")  // 开启缓存
    @Override
    public List<Category> getCategoryList() {
        List<Category> categories = baseMapper.selectList(null);
        List<Category> list = categories.stream()
                .peek(category -> category.setProducts(productService.getCategoryListByProductId(category.getId())))
                .collect(Collectors.toList());

        return this.getCategoryListById(list, 0L);
    }

    @Override
    public void exportData(HttpServletResponse response) {
        List<Category> categories = baseMapper.selectList(null);
        List<CategoryEeVO> categoryEeVOList = CategoryConverter.INSTANCE.toCategoryEeVOList(categories);
        ExcelUtils.exportDataToExcel(response, "商品分类", CategoryEeVO.class, new CategoryCellStyleHandler(), categoryEeVOList);

    }

    @CacheEvict(value = "category", allEntries = true)  // 清空缓存
    @Override
    public Boolean importData(String filepath) {
        ExcelUtils.importDataToExcel(filepath, CategoryEeVO.class, new CategoryListener(baseMapper));
        return true;
    }


    private List<Category> getCategoryListById(List<Category> list, Long parentId) {
        return list.stream()
                .filter(category -> category.getParentId().equals(parentId))
                .peek(category -> category.setChildren(this.getCategoryListById(list, category.getId())))
                .collect(Collectors.toList());
    }
}




